package com.jihui.jihuipicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jihui.jihuipicturebackend.api.ailiyunai.aliyunapi.AliYunAiApi;
import com.jihui.jihuipicturebackend.api.ailiyunai.model.CreateOutPaintingTaskRequest;
import com.jihui.jihuipicturebackend.api.ailiyunai.model.CreateOutPaintingTaskResponse;
import com.jihui.jihuipicturebackend.model.entity.Space;
import com.jihui.jihuipicturebackend.service.SpaceService;
import com.jihui.jihuipicturebackend.utils.ColorSimilarUtils;
import com.jihui.jihuipicturebackend.utils.ColorTransformStandardUtil;
import com.jihui.jihuipicturebackend.constant.UserConstant;
import com.jihui.jihuipicturebackend.exception.BusinessException;
import com.jihui.jihuipicturebackend.exception.ErrorCode;
import com.jihui.jihuipicturebackend.exception.ThrowUtils;
import com.jihui.jihuipicturebackend.manager.upload.FileManagerUploadTemplate;
import com.jihui.jihuipicturebackend.manager.upload.PictureFileUpload;
import com.jihui.jihuipicturebackend.manager.upload.PictureUrlUpload;
import com.jihui.jihuipicturebackend.model.dto.file.UploadPictureResult;
import com.jihui.jihuipicturebackend.model.dto.picture.*;
import com.jihui.jihuipicturebackend.model.entity.Picture;
import com.jihui.jihuipicturebackend.model.entity.User;
import com.jihui.jihuipicturebackend.model.enums.PictureReviewStatusEnum;
import com.jihui.jihuipicturebackend.model.vo.PictureVO;
import com.jihui.jihuipicturebackend.model.vo.UserVO;
import com.jihui.jihuipicturebackend.service.PictureService;
import com.jihui.jihuipicturebackend.mapper.PictureMapper;
import com.jihui.jihuipicturebackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wu'ji'hui
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-01-16 14:05:28
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {

    @Resource
    private UserService userService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private PictureFileUpload pictureFileUpload;

    @Resource
    private PictureUrlUpload pictureUrlUpload;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private AliYunAiApi aliYunAiApi;


    /**
     * 上传图片
     *
     * @param inputResource
     * @param pictureUploadRequest
     * @param loginUser
     * @return
     */
    @Override
    public PictureVO uploadPicture(Object inputResource, PictureUploadRequest pictureUploadRequest,
                                   User loginUser) {
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 校验空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            // 校验用户是否有权限操作空间
            ThrowUtils.throwIf(!loginUser.getId().equals(space.getUserId()), ErrorCode.NO_AUTH_ERROR, "无权限操作");
            // 校验额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }
        }
        // 用于判断是新增还是更新图片
        Long pictureId = null;
        if (ObjectUtil.isNotEmpty(pictureUploadRequest)) {
            pictureId = pictureUploadRequest.getId();
        }
        // 如果是更新图片，需要校验图片是否存在
        if (pictureId != null) {
            Picture oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            // 仅本人或管理员可编辑
            if (!oldPicture.getUserId().equals(loginUser.getId()) && !loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            // 校验空间是否一致
            // 没传 spaceId，则复用原有图片的 spaceId
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                // 传了 spaceId，必须和原有图片一致
                if (ObjUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间 id 不一致");
                }
            }
        }
        // 上传图片，得到信息
        // 按照用户 id 划分目录 => 按照空间划分目录
        String uploadPathPrefix;
        if (spaceId == null) {
            uploadPathPrefix = String.format("public/%s", loginUser.getId());
        } else {
            uploadPathPrefix = String.format("space/%s", spaceId);
        }
        // 上传图片
        FileManagerUploadTemplate fileUploadManager = pictureFileUpload;
        if (inputResource instanceof String) {
            fileUploadManager = pictureUrlUpload;
        }
        UploadPictureResult uploadPictureResult = fileUploadManager.uploadPicture(inputResource, uploadPathPrefix);

        // 构造要入库的图片信息
        Picture picture = new Picture();
        picture.setSpaceId(spaceId);
        // 如果是管理员上传图片，图片自动过审
        this.reviewStatus(picture, loginUser);
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        // 自定义填充图片名称
        String picName = uploadPictureResult.getPicName();
        if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getFileName())) {
            picName = pictureUploadRequest.getFileName();
        }
        // 填充色调
//        picture.setPicColor(uploadPictureResult.getPicColor());
        picture.setPicColor(ColorTransformStandardUtil.rgb565ToRgb888String(uploadPictureResult.getPicColor()));
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());
        // 如果 pictureId 不为空，表示更新，否则是新增
        if (pictureId != null) {
            // 如果是更新，需要补充 id 和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        // 保存图片的同时，更新空间的条数和大小
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            boolean result = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return picture;
        });
        return PictureVO.objToVo(picture);
    }


    /**
     * 根据 id 删除图片
     *
     * @param pictureId
     * @return
     */
    @Override
    public boolean deletePictureById(Long pictureId, User loginUser) {
        // 根据 id 查询图片是否存在
        Picture picture = this.getById(pictureId);
        ThrowUtils.throwIf(picture == null, new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在"));
        // 校验用户是否有权限操作图片
        checkPictureAuth(loginUser, picture);
        // 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(pictureId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            // 释放额度
            Long spaceId = picture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + picture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // 根据图片 id 删除图片
        String pictureUrl = picture.getUrl();
        // 找到最后一个斜杠的位置
        int startIndex = pictureUrl.indexOf("/public");
        if(pictureUrl.contains("/space")){
            startIndex = pictureUrl.indexOf("/space");
        }
        // 提取从最后一个斜杠开始的子字符串
        String key = pictureUrl.substring(startIndex);
        // 删除cos存储的图片
        FileManagerUploadTemplate fileManagerUploadTemplate = pictureFileUpload;
        fileManagerUploadTemplate.deletePicture(key);
        baseMapper.deleteById(pictureId);
        return true;
    }

    /**
     * 更新图片
     *
     * @param multipartFile
     * @param pictureUpdateRequest
     * @param loginUser
     * @return
     */
    @Override
    public PictureVO updatePicture(MultipartFile multipartFile, PictureUpdateRequest pictureUpdateRequest,
                                   User loginUser) {
        // 校验图片上传请求
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 用于判断是新增还是更新图片
        Long pictureId = null;
        if (pictureUpdateRequest != null) {
            pictureId = pictureUpdateRequest.getId();
        }
        // 更新图片，需要校验图片是否存在
        if (pictureId != null) {
            // 仅用户本人和管理员可以更新图片
            Picture oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            checkPictureAuth(loginUser, oldPicture);
        }

        // 更新本地数据库中的图片信息
        Picture picture = this.getById(pictureId);
        BeanUtil.copyProperties(pictureUpdateRequest, picture);
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));

        // 按照用户 id 划分目录
        String uploadPathPrefix = String.format("public/%s", loginUser.getId());
        FileManagerUploadTemplate fileManagerUploadTemplate = pictureFileUpload;
        UploadPictureResult uploadPictureResult = fileManagerUploadTemplate.uploadPicture(multipartFile, uploadPathPrefix);
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setName(uploadPictureResult.getPicName());
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());

        // 重置审核状态
        this.reviewStatus(picture, loginUser);
        // 更新数据库
        boolean result = this.saveOrUpdate(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
        return PictureVO.objToVo(picture);
    }

    /**
     * 构造查询条件
     *
     * @param pictureQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Picture> getPictureQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isEmpty(pictureQueryRequest)) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();


        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 获取单个图片信息
     *
     * @param picture
     * @param request
     * @return
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }


    /**
     * 管理员获取分页图片列表
     *
     * @param picturePage
     * @param httpServletRequest
     * @return
     */
    @Override
    public Page<PictureVO> getPictureListVO(Page<Picture> picturePage, HttpServletRequest httpServletRequest) {
        List<Picture> pictureRecords = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(),
                picturePage.getTotal());
        if (CollUtil.isEmpty(pictureRecords)) {
            return pictureVOPage;
        }
        // picture 转 pictureVO
        List<PictureVO> pictureVOList = pictureRecords.stream().map(PictureVO::objToVo).collect(Collectors.toList());

        // 补充用户信息
        // 1. 关联查询用户信息
        // 先从 picture 中取出所有用户 id
        Set<Long> userIdSet = pictureRecords.stream().map(Picture::getUserId).collect(Collectors.toSet());
        // 再根据 id 集合查询所有用户信息
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            // 脱敏处理
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            pictureVO.setUser(userVO);
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    /**
     * 校验图片信息
     *
     * @param picture
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    /**
     * 管理员审核图片
     *
     * @param pictureReviewStatusRequest
     * @param loginUser
     * @return
     */
    @Override
    public boolean pictureReviewStatus(PictureReviewStatusRequest pictureReviewStatusRequest, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        ThrowUtils.throwIf(pictureReviewStatusRequest == null, ErrorCode.PARAMS_ERROR);
        // 根据 id 查询图片是否存在
        Long pictureId = pictureReviewStatusRequest.getId();
        ThrowUtils.throwIf(pictureId == null, ErrorCode.PARAMS_ERROR, "图片 id 为空");
        Picture picture = this.getById(pictureId);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        // 校验审核状态
        ThrowUtils.throwIf(picture.getReviewStatus()
                        .equals(pictureReviewStatusRequest.getReviewStatus()),
                ErrorCode.PARAMS_ERROR, "请不要重复审核");
        // 更新审核状态
        Picture pictureUpdate = new Picture();
        // 只需要更新审核状态和审核时间，其他字段不用更新，减轻数据库压力
        BeanUtil.copyProperties(pictureReviewStatusRequest, pictureUpdate);
        pictureUpdate.setReviewerId(loginUser.getId());
        pictureUpdate.setReviewTime(new Date());
        boolean result = this.updateById(pictureUpdate);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "审核失败");
        return true;
    }

    /**
     * 重置图片审核状态
     *
     * @param picture
     * @param loginUser
     */
    @Override
    public void reviewStatus(Picture picture, User loginUser) {
        if (loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE)) {
            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(new Date());
        } else {
            // 非管理员，创建或编辑都要改为待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    /**
     * 通过搜索词批量上传图片
     *
     * @param pictureUploadByBatchRequest
     * @param loginUser
     * @return
     */
    @Override
    /*public int pictureUploadByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest,
                                    User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(ObjectUtil.isEmpty(loginUser), new BusinessException(ErrorCode.NO_AUTH_ERROR,"无权限操作"));
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, new BusinessException(ErrorCode.PARAMS_ERROR,"参数错误"));

        // 获取参数信息
        Integer count = pictureUploadByBatchRequest.getCount();
        String searchText = pictureUploadByBatchRequest.getSearchText();
        String picPrefix = pictureUploadByBatchRequest.getPicPrefix();

        // 校验参数
        ThrowUtils.throwIf(count > 30, new BusinessException(ErrorCode.PARAMS_ERROR,"一次上传图片数量不能超过30张"));

        // 通过Jsoup抓取图片
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        }catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setFileName(picPrefix + (uploadCount + 1));
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功, id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;

    }*/
    public int pictureUploadByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest,
                                    User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(ObjectUtil.isEmpty(loginUser), new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作"));
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误"));

        // 获取参数信息
        Integer count = pictureUploadByBatchRequest.getCount();
        String searchText = pictureUploadByBatchRequest.getSearchText();
        String picPrefix = pictureUploadByBatchRequest.getPicPrefix();
        Integer startIndex = pictureUploadByBatchRequest.getStartIndex() != null ? pictureUploadByBatchRequest.getStartIndex() : 0;

        // 校验参数
        ThrowUtils.throwIf(count > 30, new BusinessException(ErrorCode.PARAMS_ERROR, "一次上传图片数量不能超过30张"));

        // 通过Jsoup抓取图片
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;
        int currentIndex = 0;

        for (Element imgElement : imgElementList) {
            if (currentIndex < startIndex) {
                currentIndex++;
                continue;
            }

            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                currentIndex++;
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setFileName(picPrefix + (startIndex + uploadCount + 1));
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功, id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                currentIndex++;
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
            currentIndex++;
        }
        return uploadCount;
    }

    /**
     * 检查图片权限
     *
     * @param loginUser
     * @param picture
     */
    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        if (spaceId != null) {//如果图片有空间，则判断是私有空间图片
            ThrowUtils.throwIf(!loginUser.getId().equals(picture.getUserId()), ErrorCode.NO_AUTH_ERROR, "无权限操作");
        } else {//如果图片没有空间，则判断是公开图片，仅管理员和用户本人可以访问
            ThrowUtils.throwIf(!loginUser.getId().equals(picture.getUserId())
                            && !loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE),
                    ErrorCode.NO_AUTH_ERROR, "无权限操作");
        }
    }

    /**
     * 根据图片主色调获取图片列表
     *
     * @param spaceId
     * @param picColor
     * @param loginUser
     * @return
     */
    @Override
    public List<PictureVO> getPictureListByColor(Long spaceId, String picColor, User loginUser) {
        // 参数校验
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        // 空间权限校验
        // 1. 空间是否存在
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        // 2. 是否有空间权限
        long userId = loginUser.getId();
        ThrowUtils.throwIf(userId != space.getUserId(), ErrorCode.NO_AUTH_ERROR, "无权限访问该空间");
        // 查询数据库中有色调的图片列表
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        // 根据图片列表中的色调相似度排序
        if (CollUtil.isEmpty(pictureList)) {
            return Collections.emptyList();
        }
        // 将目标颜色转为 Color 对象
        Color targetColor = Color.decode(picColor);
        // 4. 计算相似度并排序
        List<PictureVO> sortedPictures = pictureList.stream()
                .sorted(Comparator.comparingDouble(picture -> {
                    // 提取图片主色调
                    String hexColor = picture.getPicColor();
                    // 没有主色调的图片放到最后
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    Color pictureColor = Color.decode(hexColor);
                    // 越大越相似
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                }))
                // 取前 12 个
                .limit(12)
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());

        // 转换为 PictureVO
        return sortedPictures;
    }

    /**
     * AI 阔图任务创建
     *
     * @param createPictureOutPaintingTaskRequest
     * @param loginUser
     * @return
     */
    @Override
    public CreateOutPaintingTaskResponse createOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest,
                                                               User loginUser) {
        // 获取参数
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
//        if(pictureId == null){
//            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图片id不能为空");
//        }
//        Picture picture = this.getById(pictureId);
//        if(picture == null){
//            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"图片不存在");
//        }
        Picture picture = Optional.ofNullable(this.getById(pictureId)).orElseThrow(
                () -> new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在"));
        // 校验权限
        checkPictureAuth(loginUser, picture);
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }

}




